package com.wyu.dao;

import com.alibaba.druid.util.JdbcUtils;
import com.wyu.pojo.SC;
import com.wyu.pojo.YG;
import com.wyu.util.GetCt;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

public class SCDaoImpl implements SCDao {
    @Override
    public List<SC> searchsc() {
        QueryRunner qr = new QueryRunner();
        Connection ct = null;
        //获得数据库连接，德鲁伊数据源
        try {
            ct = GetCt.getConnection();
            String sql = "select * from scb  ";
            List<String> list1 = new ArrayList<>();
            BeanListHandler<SC> handler = new BeanListHandler(SC.class);
            List<SC> list = qr.query(ct,sql,handler,list1.toArray());
            System.out.println(list);
            return list;
        } catch (Exception exception){
            exception.printStackTrace();
        }finally {
            JdbcUtils.close(ct);
        }
        return null;
    }

    @Override
    public int updateSc(String scbh, String zs, String kc) {
        QueryRunner qr = new QueryRunner();
        Connection ct = null;
        try {
            ct =  GetCt.getConnection();
            String sql = "update scb set zs=?,kc=? where scbh=?;";
            int i =  qr.update(ct,sql,zs,kc,scbh);
            if(i>0){
                System.out.println("修改成功"+i+"条数据");
                return 1;
            }
        } catch (Exception exception){
            exception.printStackTrace();
        }finally {
            JdbcUtils.close(ct);
        }
        return 0;
    }

    @Override
    public List<SC> selectBypage(int start, int count) {
        QueryRunner qr = new QueryRunner();
        Connection ct = null;
        SC sc = null;
        //获得数据库连接，德鲁伊数据源
        try {
            ct = GetCt.getConnection();
            String sql = "select * from scb where  limit ?,?;";
            BeanListHandler<SC> handler = new BeanListHandler(SC.class);
            List<SC> list = qr.query(ct,sql,handler,start,count);
            list.forEach(li -> System.out.println(li));
            return list;
        } catch (Exception exception){
            exception.printStackTrace();
        }finally {
            JdbcUtils.close(ct);
        }
        return null;
    }

    @Override
    public int selectByCount() {
        QueryRunner qr = new QueryRunner();
        Connection ct = null;
        SC sc = null;
        //获得数据库连接，德鲁伊数据源
        try {
            ct = GetCt.getConnection();
            String sql = "select count(*) count from scb ";
            return ((Long)qr.query(ct,sql,new ScalarHandler<>())).intValue();
        } catch (Exception exception){
            exception.printStackTrace();
        }finally {
            JdbcUtils.close(ct);
        }
        return 0;
    }
}
